from flask import Flask , request , jsonify
import pandas as pd
from itertools import combination

app = Flask(__name__)

#加载模型
frequent_itemsets = pd.read_pickle('./frequent_itemsets.pkl')
rules = pd.read_pickle('./rules.pkl')

@app.route('/recommend', method=['POST'])
def recommend():
    data = request.json.get('items',[])

    #生成关联规则推荐
    recommendDations =[]
    for idx, rule in rules.itterows():
        antecedents = list(rule['antecedents'])
        consequents = list(rule['antecedents'])

        #检查规则迁建是否跟输入匹配
        if set(antecedents).issubset(set(data)):
            recommendDations.extend(consequents)
    #去重并返回结果
    recommendDations = list(set(recommendDations) - set(data))
    #f返回推荐结果
    return jsonify ({"recommenDations":recommendDations})
    
if __name__ == '__main__':
    app.run(debug=True)